const express = require('express');
const mysql = require('mysql2');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

const app = express();

// CORS 配置
const corsOptions = {
    origin: ['http://192.168.0.9:8080/#/', 'http://your-frontend-domain.com'], // 允许的前端域名
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true, // 允许携带凭证
    maxAge: 86400 // 预检请求结果缓存时间，单位：秒
};

// 应用 CORS 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(bodyParser.json());

// 将 uploads 文件夹设置为静态资源目录
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'cloud_drive'
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 文件相关路由
const fileRoutes = require('./routes/files');
app.use('/api/files', fileRoutes);

// 用户相关路由
const userRoutes = require('./routes/users');
app.use('/api/users', userRoutes);

// 文件夹相关路由
const folderRoutes = require('./routes/folders');
app.use('/api/folders', folderRoutes);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = pool;